package com.mercury.auth.endpoint;

import cn.hutool.core.util.StrUtil;
import com.mercury.base.result.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;


/**
 * @author mercury
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/token")
@Api(tags = "权限")
public class AuthTokenEndPoint {

    private final TokenStore tokenStore;


    /**
     * 退出并删除token
     *
     * @param authHeader Authorization
     */
    @ApiOperation("退出")
    @DeleteMapping("/logout")
    public ResultVo<Boolean> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
        if (StrUtil.isBlank(authHeader)) {
            return ResultVo.ok();
        }

        String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
        return removeToken(tokenValue);
    }


    private ResultVo<Boolean> removeToken(String token) {
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
            return ResultVo.ok();
        }
        // 清空access token
        tokenStore.removeAccessToken(accessToken);

        // 清空 refresh token
        OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
        tokenStore.removeRefreshToken(refreshToken);
        return ResultVo.ok();
    }


}
